package org.lionzhou.chatGG.web.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lionzhou.chatGG.web.client.dto.ChatDto;
import org.lionzhou.chatGG.web.client.dto.ChatResDto;
import org.lionzhou.chatGG.web.config.GGConfig;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

/**
 * @Description
 * @Author ZhouLiangCheng
 * @Date 2023/2/10
 * @Version 1.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class ChatGptClient {

    ObjectMapper objectMapper;

    GGConfig ggConfig;


    public void send() {
        ChatDto chatDto = new ChatDto();
        post(chatDto);
    }

    public ChatResDto post(ChatDto chatDto) {
        try {
            String body = objectMapper.writeValueAsString(chatDto);
            log.info("body:{}", body);
            HttpRequest httpRequest = HttpRequest.newBuilder()
                    .timeout(Duration.ofSeconds(900))
                    .uri(URI.create("https://api.openai.com/v1/completions"))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + ggConfig.getAccessToken())
                    .POST(HttpRequest.BodyPublishers.ofString(body))
                    .build();
            HttpResponse.BodyHandler<byte[]> bodyHandler = HttpResponse.BodyHandlers.ofByteArray();
            CompletableFuture<HttpResponse<byte[]>> future = HttpClient.newHttpClient().sendAsync(httpRequest, bodyHandler);

            ChatResDto resDto = future.thenApply(HttpResponse::body)
                    .thenApply((r) -> {
                        log.info(new String(r));
                        ChatResDto chatResDto = null;
                        try {
                            chatResDto = objectMapper.readValue(r, ChatResDto.class);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        log.info(chatResDto.toString());
                        return chatResDto;
                    })
                    .join();

            return resDto;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
